package com.landinfo.web.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.codahale.metrics.annotation.Timed;
import com.landinfo.domain.User;
import com.landinfo.service.UserService;
import com.landinfo.service.ViewDataManageService;
import com.landinfo.service.dto.ViewDataManageDTO;
import com.landinfo.web.rest.vm.ViewDataManageVM;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * REST controller for managing ViewDataManage.
 */
@RestController
@RequestMapping("/api")
public class ViewDataManageResource {

    private final Logger log = LoggerFactory.getLogger(ViewDataManageResource.class);

    private static final String ENTITY_NAME = "viewDataManage";

    private final ViewDataManageService viewDataManageService;
    private final UserService userService;

    public ViewDataManageResource(
        ViewDataManageService viewDataManageService,
        UserService userService
    ) {
        this.viewDataManageService = viewDataManageService;
        this.userService = userService;
    }

    @PostMapping("/view-data-manages")
    @Timed
    public String createViewDataManage(@RequestBody ViewDataManageDTO data) {
        User user = userService.getUserWithAuthorities();
        if (user == null) {
            throw new BadCredentialsException("Invalid token");
        }
        JSONObject result = new JSONObject();
        result.put("success", false);
        result.put("exist", false);
        if (data.getPosition() == null || data.getPosition().equals("") || data.getCode() == null || data.getCode().equals("")) {
            result.put("msg", "缺少参数！");
            return JSON.toJSONString(result);
        }
        try {
            // 判断期数编号是否重复
            Optional<ViewDataManageDTO> find = viewDataManageService.findByCodeAndPosition(data.getCode(), data.getPosition());
            if (find.isPresent()) {
                if (data.getCoverOld() != null && data.getCoverOld()) {
                    data.setId(find.get().getId());
                } else {
                    result.replace("exist", true);
                    result.put("msg", "该位置对应数据已存在！");
                    return JSON.toJSONString(result);
                }
            }
            ViewDataManageDTO saveResult = viewDataManageService.save(data);
            result.replace("success", true);
            result.put("msg", "保存成功！");
            return JSON.toJSONString(result);
        } catch (Exception ex) {
            String message = ex.getLocalizedMessage();
            result.put("msg", "保存失败！" + message);
            return JSON.toJSONString(result);
        }
    }

    @PutMapping("/view-data-manages")
    @Timed
    public String updateViewDataManage(@RequestBody ViewDataManageDTO data) {
        User user = userService.getUserWithAuthorities();
        if (user == null) {
            throw new BadCredentialsException("Invalid token");
        }
        JSONObject result = new JSONObject();
        result.put("success", false);
        if (data.getPosition() == null || data.getPosition().equals("") || data.getCode() == null || data.getCode().equals("")) {
            result.put("msg", "缺少参数！");
            return JSON.toJSONString(result);
        }
        if (data.getId() == null) {
            result.put("msg", "传入id为空！");
        } else if (!viewDataManageService.findOne(data.getId()).isPresent()) {
            result.put("msg", "该数据不存在！");
        } else {
            Optional<ViewDataManageDTO> find = viewDataManageService.findByCodeAndPosition(data.getCode(), data.getPosition());
            if (find.isPresent() && !find.get().getId().equals(data.getId())) {
                result.put("exist", true);
                result.put("msg", "该位置对应数据已存在！");
                return JSON.toJSONString(result);
            }
            try {
                ViewDataManageDTO saveResult = viewDataManageService.save(data);
                result.replace("success", true);
                result.put("msg", "修改成功！");
            } catch (Exception ex) {
                String message = ex.getLocalizedMessage();
                result.put("msg", "修改失败！" + message);
                return JSON.toJSONString(result);
            }
        }
        return JSON.toJSONString(result);
    }

    // 查询列表
    @PostMapping("/view-data-manages/queryList")
    public String queryList(@RequestBody ViewDataManageVM param) {
        User user = userService.getUserWithAuthorities();
        if (user == null) {
            throw new BadCredentialsException("Invalid token");
        }
        JSONObject result = viewDataManageService.queryList(param);
        return JSON.toJSONString(result);
    }

    @GetMapping("/view-data-manages/fandByCode/{position}/{code}")
    @Timed
    public String getViewDataByCode(@PathVariable String position, @PathVariable String code) {
        User user = userService.getUserWithAuthorities();
        if (user == null) {
            throw new BadCredentialsException("Invalid token");
        }
        JSONObject result = new JSONObject();
        Optional<ViewDataManageDTO> viewDataManageDTO = viewDataManageService.findByCodeAndPosition(code, position);
        result.put("data", viewDataManageDTO);
        result.put("success", viewDataManageDTO.isPresent());
        return JSON.toJSONString(result);
    }

    @GetMapping("/view-data-manages/{id}")
    @Timed
    public ResponseEntity<ViewDataManageDTO> getViewDataManage(@PathVariable String id) {
        User user = userService.getUserWithAuthorities();
        if (user == null) {
            throw new BadCredentialsException("Invalid token");
        }
        Optional<ViewDataManageDTO> viewDataManageDTO = viewDataManageService.findOne(id);
        return ResponseUtil.wrapOrNotFound(viewDataManageDTO);
    }

    @DeleteMapping("/view-data-manages/{id}")
    @Timed
    public String deleteViewDataManage(@PathVariable String id) {
        User user = userService.getUserWithAuthorities();
        if (user == null) {
            throw new BadCredentialsException("Invalid token");
        }
        JSONObject result = new JSONObject();
        try {
            viewDataManageService.delete(id);
            result.put("success", true);
            result.put("msg", "删除成功");
            return JSON.toJSONString(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "删除失败");
            return JSON.toJSONString(result);
        }
    }
}
